<template>
  <a-spin :spinning="confirmLoading">
      <a-row>
        <a-col :span="10">
          招标项目编号 :
          {{ exTenderFileInfo.tenderProjectCode }}
        </a-col>
        <a-col :span="10">
          标段编号：
          {{ exTenderFileInfo.bidSectionCode }}
        </a-col>
      </a-row>
      <a-row type="flex" style="margin-top: 10px">
        <a-col flex="400px">
          <a-card  :body-style="{ padding: '0px',minHeight:'640px' }">
            <chapter-list
              ref="chapterRef"
              @change="chapterChange"
              @clearNoticeContent="noticeContent = null"
              :projectId="exTenderFileInfo.projectId"
              :sectionId="exTenderFileInfo.sectionId"
              :isChanged="isChanged"
            />
          </a-card>
        </a-col>
        <a-col flex="10px"></a-col>
        <a-col flex="auto">
          <!-- 普通、投标函显示 -->
          <a-card :bordered="false" :body-style="{ padding: '0px' }" v-if="showEditorFlag">
            <a-row>
              <a-button style="float: right; margin-left: 8px" type="link" @click="validate">预校验</a-button>
              <!--  <a-button style="margin-left: 8px" type="primary" @click="save">保存</a-button> -->
              <a-button style="float: right" type="primary" icon="save" @click="handleSave(1)" :disabled="formDisabled"
                >保存章节</a-button
              > 
              <a-button icon="plus" type="primary" size="small" @click="insertModal" :disabled="formDisabled">插入变量</a-button>
              <a-button icon="edit" size="small" @click="exTenderFileInfoEdit" :disabled="formDisabled" style="margin-left: 8px">变量编辑</a-button>
                      <a-tag color="orange" v-if="isChanged"  style="margin-left: 8px">有修改变动请及时保存</a-tag>
            </a-row>
            <a-row style="margin-top: 10px; height: 800px">
              <j-editor ref="myEditor" v-model="noticeContent" :disabled="formDisabled" />
            </a-row>
          </a-card>
          <!-- 其他显示文件上传 -->
          <a-card v-else>
            <a-row> 
              <a-button type="primary" icon="save" @click="handleSaveFile(1)" :disabled="formDisabled">保存附件</a-button>
            </a-row>
            <a-row style="margin-top: 10px; height: 800px">
              <j-upload v-model="noticeFileContent"></j-upload>
            </a-row>
          </a-card>
        </a-col>
      </a-row>
      <a-modal width="500px" title="选择变量" :visible="visible" @ok="handleOk" @cancel="visible = false">
        <!-- <j-dict-select-tag
          style="width: 180px"
          placeholder="请选择"
          v-model="varName"
          dictCode="ex_tender_file_set_variable where 1 = 1,column_name,column_key"
        /> -->
        <a-select
          placeholder="请选择"
          v-model="varName"
          style="width: 100%"
          show-search="true"
          :filter-option="filterOption"
        >
          <a-select-option v-for="item in exTenderFileOption" :key="item.columnKey" :value="item.columnKey">
            {{ item.columnName }}
          </a-select-option>
        </a-select>
      </a-modal> 
    <!-- <footer-tool-bar>
      <a-button type="primary" @click="handleSubmit" :loading="loading">提交</a-button>
      <a-button style="margin-left: 8px" @click="handleSave">保存</a-button>
    </footer-tool-bar> -->
    <set-variable-list
      ref="refSetVariableList"
      :projectId="exTenderFileInfo.projectId"
      :sectionId="exTenderFileInfo.sectionId"
    ></set-variable-list>
  </a-spin>
</template>

<script>
import FooterToolBar from '@/components/tools/FooterToolBar'
import '@/assets/less/TableExpand.less'
import SetVariableList from '@/views/exTenderFileSetVariable/ExTenderFileSetVariableList'
import ChapterList from '@/views/exTenderFile/ChapterListMini'
import JUpload from '@/components/jeecg/JUpload'

import { httpAction, getAction } from '@/api/manage'

function findFirstTypeOne(node) {
  // 如果当前节点是数组，则迭代数组中的每个元素
  if (Array.isArray(node)) {
    for (let i = 0; i < node.length; i++) {
      let result = findFirstTypeOne(node[i])
      if (result) return result
    }
  } else if (typeof node === 'object' && node !== null) {
    // 检查当前节点是否为 type 1
    if (node.type === '投标函') {
      return node
    }

    // 如果当前节点有 children 属性，递归查找其子节点
    if (Array.isArray(node.children)) {
      for (let i = 0; i < node.children.length; i++) {
        let result = findFirstTypeOne(node.children[i])
        if (result) return result
      }
    }
  }

  // 如果没有找到 type 1 的节点，则返回 null 或 undefined
  return null
}
export default {
  name: 'exTenderFileAdd',
  components: { SetVariableList, ChapterList, FooterToolBar, JUpload },
  props: {
    entryId: {
      default: '',
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      visible: false,
      varName: null,
      oldNoticeContent:'',
      noticeContent: '',
      confirmLoading: false,
      exTenderFileId: '',
      exTenderFileInfo: { projectId: '', sectionId: '' },
      model: {},
      exTenderFileOption: [],
      url: {
        exTenderFileSetVariableList: '/exTenderFileSetVariable/exTenderFileSetVariable/list',
      },
      selectedType: null,
      noticeFileContent: null,
    }
  },
  watch: {
    entryId: {
      immediate: true,
      handler(val) {
        if (val != '' && val != undefined) {
          this.exTenderFileId = val
          this.loadExTenderFileInfo()
        }
      },
    },
  },
  computed: {
    showEditorFlag() {
      return !this.selectedType || this.selectedType == '普通' || this.selectedType == '投标函'
    },
    formDisabled() {
      return this.disabled
    },
    isChanged(){
      return this.noticeContent != this.oldNoticeContent
    }
  },
  created() {
    this.exTenderFileId = this.$route.query.exTenderFileId
    if (this.exTenderFileId) {
      this.loadExTenderFileInfo()
    } else {
    }
  },
  mounted() {
    //this.$refs.realForm.addBefore()
  },
  methods: {
    async validate() {
      // 如果没有选择章节，先保存当前内容
      if (!this.$refs.chapterRef.selectedRowKeys.length == 0) {
        await this.handleSave()
      }
      
      // 检查是否有数据源
      if (!this.$refs.chapterRef.dataSource?.length) {
        return this.$notification.warning({
          message: '提示信息',
          description: '请添加章节',
        })
      }
      
      // 加载变量列表
      let varList = await this.$refs.refSetVariableList.loadData(1, 99999)
      console.log(varList)
      
      // 检查变量列表是否为空
      if (!varList?.length) {
        return this.$notification.warning({
          message: '提示信息',
          description: '请添加变量',
        })
      }
      
      // 获取所有章节
      let chapters = this.$refs.chapterRef.dataSource
      let allValid = true
      let errorMessages = []
      console.log(chapters)
      // 递归检查章节及其子章节
      const checkChapter = async (chapter) => {
        // 检查当前章节
        await getAction('exTenderFileDetail/exTenderFileDetail/list', { categoryId: chapter.id }).then((res) => {
          if (res.success && res.result.total > 0) {
            let model = res.result.records[0]
            let noticeContent = model.content
            
            // 检查所有显示的变量是否都已插入
            let missingVars = varList
              .filter((item) => item.ifShow)
              .filter((item) => !noticeContent.includes(`<input type="text" value="${item.columnKey}" />`))
            
            if (missingVars.length > 0) {
              allValid = false
              errorMessages.push(`${chapter.name} 缺少变量: ${missingVars.map(v => v.columnName).join(', ')}`)
            }
          } else {
            allValid = false
            errorMessages.push(`${chapter.name} 缺少内容`)
          }
        })
          // 如果有子章节，递归检查
    if (chapter.children && chapter.children.length > 0) {
      for (let child of chapter.children) {
        await checkChapter(child)
      }
    }
      }
      // 遍历所有章节
      for (let chapter of chapters) {
        await checkChapter(chapter)
      }
      // 显示校验结果
      if (allValid) {
        this.$notification.success({ message: '提示信息', description: '所有章节预校验成功' })
      } else {
        this.$notification.warning({
          message: '提示信息',
          description: errorMessages.join('\n')
        })
      }
    },
    handleCancel() {
      this.close()
    },
    loadExTenderFileInfo() {
      var that = this
      getAction('exTenderFileClariModi/exTenderFileClariModi/queryById?id=' + that.exTenderFileId)
        .then((res) => {
          if (res.success) {
            that.exTenderFileInfo = res.result
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    insertModal() {
      var that = this
      this.varName = ''
      //todo 加载变量
      var params = {}
      params.projectId = this.exTenderFileInfo.projectId
      params.sectionId = this.exTenderFileInfo.sectionId
      params.pageSize = 9999
      this.loading = true
      getAction(this.url.exTenderFileSetVariableList, params)
        .then((res) => {
          if (res.success) {
            that.exTenderFileOption = res.result.records || res.result
          } else {
            this.$message.warning(res.message)
          }
          that.visible = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleOk() {
      const editor = this.$refs.myEditor.editor
      if (editor) {
        // 在当前光标位置插入内容
        editor.insertContent('<input type="text" value="' + this.varName + '"/>')
      }
      console.log('ok')
      this.visible = false
    },
    handleSubmit() {
      this.handleSave()
    },
    async handleSave(showMsg) {
      var that = this
      if (that.$refs.chapterRef.selectedRowKeys.length == 0) {
        that.$message.warning('请选择分类')
        return
      }
      var cid = that.$refs.chapterRef.selectedRowKeys[0]
      var url = 'exTenderFileDetail/exTenderFileDetail/add'
      var param = { content: that.noticeContent, categoryId: cid }
      if (that.model && that.model.id) {
        param.id = that.model.id
        url = 'exTenderFileDetail/exTenderFileDetail/edit'
      }
      return httpAction(url, param, 'post')
        .then((res) => {
          if (showMsg) {
            if (res.success) {
              if (that.model) {
                that.model.id = res.result
              } else {
                that.model = { id: res.result }
              }
              that.oldNoticeContent = that.noticeContent
              that.$message.success(res.message)
            } else {
              that.$message.warning(res.message)
            }
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    handleSaveFile() {
      var that = this
      if (that.$refs.chapterRef.selectedRowKeys.length == 0) {
        that.$message.warning('请选择分类')
        return
      }
      if (!that.noticeFileContent) {
        that.$message.warning('请上传文件')
        return
      }
      var cid = that.$refs.chapterRef.selectedRowKeys[0]
      var url = 'exTenderFileDetail/exTenderFileDetail/add'
      var param = { content: that.noticeFileContent, categoryId: cid }
      if (that.model && that.model.id) {
        param.id = that.model.id
        url = 'exTenderFileDetail/exTenderFileDetail/edit'
      }
      return httpAction(url, param, 'post')
        .then((res) => {
          if (res.success) {
            if (that.model) {
              that.model.id = res.result
            } else {
              that.model = { id: res.result }
            }
            that.$message.success(res.message)
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    async chapterChange(selectVal, keys, select) { 
      this.selectedType = ''
      if (select) {
        console.log(select, select)
        this.selectedType = select.type
      }
      if (keys?.length) {
        // await this.handleSave()
      }

      var that = this
      that.confirmLoading = true
      getAction('exTenderFileDetail/exTenderFileDetail/list', { categoryId: selectVal })
        .then((res) => {
          if (res.success) {
            that.model = null
            that.noticeContent = ''
            that.oldNoticeContent = ''
            that.noticeFileContent = ''
            if (res.result.total > 0) {
              that.model = res.result.records[0]
              if (this.showEditorFlag) {
                that.noticeContent = that.model.content
              } else {
                that.noticeFileContent = that.model.content
              }
            }
            that.oldNoticeContent = that.noticeContent
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    exTenderFileInfoEdit() {
      this.$refs.refSetVariableList.show()
    },
  },
}
</script>

<style scoped></style>
